//
//  HeartRateChartView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/8/1.
//

import SwiftUI
import Charts


struct HDataItem : Identifiable{
    let id = UUID()
    let timeRange: String
    let higthValue: Double
    let lowValue: Double
    
    
    
    
}


struct HeartRateChartView: View {
    let data: [HDataItem]
    private let maxScore: Double = 100

    var body: some View {
            Chart(data) { item in
                BarMark(
                    x: .value("时间", item.timeRange),
                    yStart: .value("最低值", item.lowValue),
                    yEnd: .value("最高值", item.higthValue),
                    width: .ratio(0.5)
                )
                .foregroundStyle(Color(hex: "#E96644"))
            }
            .chartXScale(domain: data.map { $0.timeRange })
            .chartXAxis {
                AxisMarks(values: .automatic) { value in
                    if  value.index < data.count - 1 {
                        AxisGridLine( stroke: StrokeStyle( lineWidth: 0.5,dash: [4, 2]))
                            .foregroundStyle((value.index % 6 == 0 ) ? Color(hex: "#F5F5F5") : .clear)
                    }
                    if let time = value.as(String.self) {
                        AxisValueLabel {
                            let hour = getHourNumber(date: time)
                            if hour % 6 == 0{
                                Text(time)
                                    .foregroundStyle(Color(hex: "#C1C1C1"))
                                    .font(.system(size: 12))
                                    .frame(width: 100)
                            }
                        }
                    }
                }
            }
            .chartYScale(domain: 0...maxScore)
            .chartYAxis {
                AxisMarks(position: .trailing,values: .stride(by: 20)) { value in
                    AxisGridLine().foregroundStyle(.clear)
                    AxisTick(length: 0)
                    if let score = value.as(Double.self) {
                        AxisValueLabel {
                                Text("\(Int(score))")
                                    .foregroundStyle(Color(hex: "#C1C1C1"))
                                    .font(.system(size: 12))
                                    .padding(.leading,10)
                        }
                    }
                }
            }
            .frame(height: 200)
            .chartLegend(.hidden)
        
        }
    
    
    func getHourNumber(date:String) -> Int {
        if let colonIndex = date.firstIndex(of: ":") {
            let hourPart = date[..<colonIndex]
            print(String(hourPart))
            return Int(hourPart) ?? 0
        }
        return 0
    }
}


